import log from '../dxmodules/dxLogger.js'
import std from '../dxmodules/dxStd.js'
import mqtt from '../dxmodules/dxMqtt.js'
import * as os from "os"


let mqttAddr = "tcp://101.200.139.97:51883" //Service IP port
let clientId = "client111" //Client ID
let username = "username" //mqtt account
let password = "password"//MQTT password
let prefix = "prefix"   //prefix
let qos = 1   //qos
let willTopic = "willTopic"   //will topic
let willMessage = JSON.stringify({xxxx:'123'})  //will message
let id ='mqtt'  //handle id
let subs = ['aaa', 'bbb/ccc', 'ddddd']

//Link mqtt
mqtt.init(mqttAddr,clientId,username,password,prefix,qos,willTopic,willMessage,id)

 std.setInterval(() => {
    try {
        if (mqtt.isConnected(id) ) {
            log.info('Connection successful');
            if (subs) {
                mqtt.subscribes(subs, qos, id)
            }
            while (true) {
                // After successful connection, enter message listening mode.
                if (!mqtt.isConnected(id) ) {
                    // If not connected, exit the loop and reconnect.
                    log.info('Disconnect');
                    break
                }
                if (!mqtt.msgIsEmpty()) {
                    let msg = mqtt.receive()
                   log.info('Data received: ',JSON.stringify(msg))
                }
                os.sleep(10)
            }
        } else {
            // Reconnect
            mqtt.reconnect(willTopic, willMessage, id)
            os.sleep(1000)//Wait 1 second after reconnecting
        }
    } catch (error) {
        log.error(error, error.stack)
    }
 }, 20)


 
